package com.hrbxlh.actionImpl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.hrbxlh.dao.HomeworkTestDao;
import com.hrbxlh.dao.RelStuClassDao;
import com.hrbxlh.dao.SourceDao;
import com.hrbxlh.util.SessionValues;
import com.hrbxlh.util.pageUtil;

/**
* -------------------------------------------------------
* Copyright (c) 2017, 鑫联华信息科技股份有限公司
* All rights reserved.
* FileName：HomeworkTestActionImpl.java
* Description：作业和试验HomeworkTestActionImpl类,负责操作作业数据以及实验数据。
* History：
* Date           Author               Desc
* 2017.4.5		  xzx                 建立
* -------------------------------------------------------
*/

@Component("homeworkTestActionImpl")
@Transactional
public class HomeworkTestActionImpl {
	
	@Resource(name="sourceDao")
	private SourceDao sourceDao;
	
	@Resource(name="homeworkTestDao")
	private HomeworkTestDao homeworkTestDao;
	
	@Resource(name = "relStuClassDao")
	private RelStuClassDao relStuClassDao;
	
	@Autowired
	@Qualifier("sourceActionImpl")
	private SourceActionImpl sourceActionImpl;

	/**
	 * @description 查询某教师教的班级
	 * @param Map<String,Object> paramMap
	 * @return List classId班级id,className班级名
	 * @throws Exception
	 */
	public List<Map<String,Object>> getTeaTeachClass(Map<String, Object> paramMap) throws Exception{
		
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		try{
			list = homeworkTestDao.getTeaTeachClass(paramMap);
		}catch(Exception e){
			throw e; 
		}
		return list;
	}
	
	/**
	 * @description 查询某教师教的课程对应的班级的作业列表
	 * @param Map<String,Object> paramMap
	 * @return List 
	 * @throws Exception
	 */
	public Map<String,Object> getTeaHomeworkList(Map<String, Object> paramMap) throws Exception{
		
		Map<String, Object> resultMap = new HashMap<String,Object>();
		try{
			int pageNow = (Integer)paramMap.get("pageNow");
			int pageSize = (Integer)paramMap.get("pageSize");
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取列表信息
			List<Map<String, Object>> homeworkList = homeworkTestDao.getTeaHomeworkList(paramMap);
			resultMap.put("homeworkList", homeworkList);
			resultMap.put("pageNow", pageNow);
			//获取全部页数
			paramMap.put("pageNow", 0);
			paramMap.put("startNum", 0);
			List<Map<String, Object>> allList = homeworkTestDao.getTeaHomeworkList(paramMap);
			int totalPage = pageUtil.getTotalPage(allList, pageSize);
			resultMap.put("totalPage", totalPage);
		}catch(Exception e){
			throw e;
		}
		return resultMap;
	}
	
	/**
	 * @description 查询某教师教的课程对应的班级的实验列表
	 * @param Map<String,Object> paramMap
	 * @return List 
	 * @throws Exception
	 */
	public Map<String,Object> getTeaTestList(Map<String, Object> paramMap) throws Exception{
		
		Map<String, Object> resultMap = new HashMap<String,Object>();
		try{
			int pageNow = (Integer)paramMap.get("pageNow");
			int pageSize = (Integer)paramMap.get("pageSize");
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取列表信息
			List<Map<String, Object>> homeworkList = homeworkTestDao.getTeaTestList(paramMap);
			resultMap.put("testList", homeworkList);
			resultMap.put("pageNow", pageNow);
			//获取全部页数
			paramMap.put("pageNow", 0);
			paramMap.put("startNum", 0);
			List<Map<String, Object>> allList = homeworkTestDao.getTeaTestList(paramMap);
			int totalPage = pageUtil.getTotalPage(allList, pageSize);
			resultMap.put("totalPage", totalPage);
		}catch(Exception e){
			throw e;
		}
		return resultMap;
	}
	
	/**
	 * @description 查询某教师教的课程的某班级的作业详情情况（作业管理列表内页）
	 * @param Map<String,Object> paramMap
	 * @return List 
	 * @throws Exception
	 */
	public Map<String,Object> getHomeWorkByClass(Map<String, Object> paramMap) throws Exception{
		
		Map<String, Object> resultMap = new HashMap<String,Object>();
		try{
			int pageNow = (Integer)paramMap.get("pageNow");
			int pageSize = (Integer)paramMap.get("pageSize");
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取列表信息
			List<Map<String, Object>> homeworkList = homeworkTestDao.getHomeWorkByClass(paramMap);
			resultMap.put("homeworkList", homeworkList);
			resultMap.put("pageNow", pageNow);
			//获取全部页数
			paramMap.put("pageNow", 0);
			paramMap.put("startNum", 0);
			List<Map<String, Object>> allList = homeworkTestDao.getHomeWorkByClass(paramMap);
			int totalPage = pageUtil.getTotalPage(allList, pageSize);
			resultMap.put("totalPage", totalPage);
		}catch(Exception e){
			throw e;
		}
		return resultMap;
	}
	
	/**
	 * @description 查询某教师教的课程的某班级的实验详情情况（实验管理列表内页）
	 * @param Map<String,Object> paramMap
	 * @return List 
	 * @throws Exception
	 */
	public Map<String,Object> getTestByClass(Map<String, Object> paramMap) throws Exception{
		
		Map<String, Object> resultMap = new HashMap<String,Object>();
		try{
			int pageNow = (Integer)paramMap.get("pageNow");
			int pageSize = (Integer)paramMap.get("pageSize");
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取列表信息
			List<Map<String, Object>> homeworkList = homeworkTestDao.getTestByClass(paramMap);
			resultMap.put("testList", homeworkList);
			resultMap.put("pageNow", pageNow);
//			//获取全部页数
			paramMap.put("pageNow", 0);
			paramMap.put("startNum", 0);
			List<Map<String, Object>> allList = homeworkTestDao.getTestByClass(paramMap);
			int totalPage = pageUtil.getTotalPage(allList, pageSize);
			resultMap.put("totalPage", totalPage);
		}catch(Exception e){
			throw e;
		}
		return resultMap;
	}
	
	/**
	 * @description 评价作业
	 * @param Map<String,Object> paramMap
	 * @return boolean true成功  false失败 
	 * @throws Exception
	 */
	public Map<String, Object> assessHomework(Map<String, Object> paramMap,HttpServletRequest request) throws Exception{
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try{//获取审核教师的id
			//获取登录人id
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"stuorteaId"}, request);
			paramMap.put("checkId", sessionValues.get("stuorteaId"));
			//查看登录的老师有没有设置成绩的等级
			Map<String, Object> teacherMapUse = new HashMap<String, Object>();
			teacherMapUse.put("stuorteaId", sessionValues.get("stuorteaId"));
			Map<String, Object> levelValuesBefore = sourceDao.getProWedith(teacherMapUse);
			if(levelValuesBefore != null){
				//将教师的评语转义了
				String teaMsg = (String)paramMap.get("submitContent");
				teaMsg = teaMsg.replaceAll("\n", "<br>");
				teaMsg = teaMsg.replaceAll("\r", "<br>");
				paramMap.put("submitContent", teaMsg);
				//代表作业标识
				paramMap.put("taskType", 1);
				//获取优良中差的对应分值
				Map<String, Object> teacherMap = new HashMap<String, Object>();
				teacherMap.put("stuorteaId", sessionValues.get("stuorteaId"));
				Map<String, Object> levelValues = sourceDao.getProWedith(teacherMap);
				//获取我填写的等级文字
				String myLevel = (String)paramMap.get("taskFraction");
				int myLevelNum = 0; 
				Map<String, Object> levelMap = this.getLevelMark(new String[]{"优","良","中","差"}, new String[]{"excellent","good","inso","bad"}, levelValues);
				myLevelNum = (Integer)levelMap.get(myLevel);
				paramMap.put("taskSoruce", myLevelNum);
				homeworkTestDao.assessHomeworkTest(paramMap);
				//查询这个学生这个课程所对应的平时分总分
				Map<String, Object> gradeMap = homeworkTestDao.getStuProfomaceGrade(paramMap);
				//保存该学生的平时分
				List<Map<String, Object>> relationList = homeworkTestDao.getStuReCourseExam(paramMap);
				//原来有就修改，没有就新增
				if(relationList != null && relationList.size() != 0){
					homeworkTestDao.saveStuReCourseExam(gradeMap);
				}else{
					//查询这个学生与这个课的关联关系
					//获取登录人与这个课的关门联标识
					Map<String, Object> relationMap = homeworkTestDao.getRelationMark(gradeMap);
					gradeMap.put("couSelectMark", relationMap.get("couSelectMark"));
					homeworkTestDao.addStuReCourseExam(gradeMap);
				}
				resultMap.put("result", true);
			}else{
				resultMap.put("result", false);
				resultMap.put("failMsg", "未设置成绩等级");
			}
		}catch(Exception e){
			throw e;
		}
		return resultMap;
	}
	
	/**
	 * @description 评价实验
	 * @param Map<String,Object> paramMap
	 * @return boolean true成功  false失败 
	 * @throws Exception
	 */
	public Map<String, Object> assessTest(Map<String, Object> paramMap,HttpServletRequest request) throws Exception{
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try{
			//获取登录人id
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"stuorteaId"}, request);
			paramMap.put("checkId", sessionValues.get("stuorteaId"));
			//查看登录的老师有没有设置成绩的等级
			Map<String, Object> teacherMapUse = new HashMap<String, Object>();
			teacherMapUse.put("stuorteaId", sessionValues.get("stuorteaId"));
			Map<String, Object> levelValuesBefore = sourceDao.getProWedith(teacherMapUse);
			if(levelValuesBefore != null){
				//将教师的评语转义了
				String teaMsg = (String)paramMap.get("submitContent");
				teaMsg = teaMsg.replaceAll("\n", "<br>");
				teaMsg = teaMsg.replaceAll("\r", "<br>");
				paramMap.put("submitContent", teaMsg);
				//代表实验标识
				paramMap.put("taskType", 2);
				//获取优良中差的对应分值
				//获取优良中差的对应分值
				Map<String, Object> teacherMap = new HashMap<String, Object>();
				teacherMap.put("stuorteaId", sessionValues.get("stuorteaId"));
				Map<String, Object> levelValues = sourceDao.getProWedith(teacherMap);
				//获取我填写的等级文字
				String myLevel = (String)paramMap.get("taskFraction");
				int myLevelNum = 0;
				Map<String, Object> levelMap = this.getLevelMark(new String[]{"优","良","中","差"}, new String[]{"excellent","good","inso","bad"}, levelValues);
				myLevelNum = (Integer)levelMap.get(myLevel);
				paramMap.put("taskSoruce", myLevelNum);
				homeworkTestDao.assessHomeworkTest(paramMap);
				//查询这个学生这个课程所对应的平时分总分
				Map<String, Object> gradeMap = homeworkTestDao.getStuProfomaceGrade(paramMap);
				//保存该学生的平时分
				List<Map<String, Object>> relationList = homeworkTestDao.getStuReCourseExam(paramMap);
				//原来有就修改，没有就新增
				if(relationList != null && relationList.size() != 0){
					homeworkTestDao.saveStuReCourseExam(gradeMap);
				}else{
					homeworkTestDao.addStuReCourseExam(gradeMap);
				}
				resultMap.put("result", true);
			}else{
				resultMap.put("result", false);
				resultMap.put("failMsg", "未设置成绩等级");
			}
		}catch(Exception e){
			throw e;
		}
		return resultMap;
	}
	
	/**
	 * @description 添加作业或实验
	 * @param Map<String,Object> paramMap
	 * @return boolean true成功  false失败 
	 * @throws Exception
	 */
	public boolean addTask(Map<String, Object> paramMap) throws Exception{
		
		boolean result = false;
		try{
			//查询是否交过作业或实验，有标识
			List<Map<String, Object>> homeworkList = homeworkTestDao.selectMyHomework(paramMap);
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String submitTime = sdf.format(date);
			paramMap.put("submitTime", submitTime);
			//如果交过，就修改
			if(homeworkList != null && homeworkList.size() != 0){
				//修改某个学生某课程某章节作业或实验
				homeworkTestDao.saveTask(paramMap);
			//没交过，添加	
			}else{
				//查询这个学生与这个课程的关联关系信息类型，存入作业表
				Map<String, Object> relationMap = homeworkTestDao.getRelationMark(paramMap);
				paramMap.put("couSelectMark", relationMap.get("couSelectMark"));
				homeworkTestDao.addTask(paramMap);
			}
			result = true;
		}catch(Exception e){
			throw e;
		}
		return result;
	}
	
	/**
	 * @description 添加某学生某课程的平时分
	 * @param Map<String,Object> paramMap
	 * @return boolean true成功  false失败 
	 * @throws Exception
	 */
	public boolean addNormalNum(Map<String, Object> paramMap) throws Exception{
		boolean result = false;
		try{
			//获取总共的分数信息
			Map<String, Object> myDegreeMap = homeworkTestDao.getMyDegreeByCourse(paramMap);
			
			if(myDegreeMap == null){
				paramMap.put("preforSource", 0);
			}else{
				paramMap.put("preforSource", myDegreeMap.get("preforSource"));
			}
			//获取我是不是有信息
			Map<String, Object> myNormalGrade = homeworkTestDao.getMyNormalDegreeMessage(paramMap);
			if(myNormalGrade != null && myNormalGrade.get("stuorteaId") != null){
				homeworkTestDao.saveMyNormalDegree(paramMap);
			}else{
				homeworkTestDao.addMyNormalDegree(paramMap);
			}
			result = true;
		}catch(Exception e){
			throw e;
		}
		return result;
	}
	
	/**
	 * @description 给商莹封的评价作业和试验的时候，重新计算分数的方法，
	 * @param 
	 * @param 
	 * @param 
	 * @return 
	 * @throws Exception
	 */
	public boolean reCountDegree(Map<String, Object> paramMap,HttpSession session) throws Exception{
		System.out.println("paramMap"+paramMap);
		boolean result = false;
		try{
			//查询当前要评价学生所在班级所属课程(参数是学号、课程号)
			Map<String,Object> stuClaCouMap = relStuClassDao.getStuClaAndCou(paramMap);//这个结果里有班号
			System.out.println("stuClaCouMap"+stuClaCouMap);
			//查询当前班级当前课程相关学生的平时成绩(参数是班号、课程号)
			List<Map<String,Object>> stuList = sourceDao.getStuSourceList(stuClaCouMap);
			for(Map<String,Object> map : stuList){
				//平时成绩换算值(参数是班号、课程号、学生平时分)
				BigDecimal finPromaceSource = sourceActionImpl.proSource(stuClaCouMap, map,session);
				System.out.println("得到的平时分"+finPromaceSource);
				//考试成绩换算值（参数考试成绩）
				BigDecimal examSource = sourceActionImpl.examSource(stuClaCouMap, map,session);
				System.out.println("得到的考试分"+examSource);
				//学生最后的成绩
				BigDecimal finSumSource = finPromaceSource.add(examSource);
				//将和此评价学生所在同一所班级的学生总成绩重新计算后更改数据库(参数是班号、课程号)
				stuClaCouMap.put("sumSource", finSumSource);
				stuClaCouMap.put("stuorteaId", map.get("stuorteaId"));
				System.out.println("最后更改的参数"+stuClaCouMap);
				sourceDao.updateSorceBySId(stuClaCouMap);
				System.out.println("怎么回事");
			}
			result = true;
		}catch(Exception e){
			throw e;
		}
		return result;
	}

	
	/**
	 * @description 辅助方法 通过优良中差获取字段对应值信息
	 * @param 优良中差文字数组
	 * @param 数据库对应字段名数组
	 * @param 数据库获取的参数数据
	 * @return Map<String, Object> key为优良中差输入的值，value为数据库对应这个字段的值
	 * @throws Exception
	 */
	public Map<String, Object> getLevelMark(String[] args1, String[] args2, Map<String, Object> paramMap) throws Exception{
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try{
			for(int i = 0; i < args1.length; i++){
				resultMap.put(args1[i], paramMap.get(args2[i]));
			}
		}catch(Exception e){
			throw e;
		}
		return resultMap;
	}

}